package eng;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class Spider1 {
    private static final Log log = LogFactory.getLog(Spider1.class);
    
    private static final String puth = "D:/tmp/1";
    
    public static final String proxyUrl = "proxy-bj1.petrochina";
    public static final String proxyPort = "8080";
    
    // 下载文件
    public static void download(String url, String fileName) throws Exception {
        String file = puth + "/" + fileName;
        BufferedOutputStream out = null;
        byte[] bit = getByte(url);
        if (bit.length > 0) {
            try {
                out = new BufferedOutputStream(new FileOutputStream(file));
                out.write(bit);
                out.flush();
                log.info("Create File success! [" + file + "]");
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }
    
    private static byte[] getByte(String uri) throws Exception {
        HttpHost proxy = new HttpHost(proxyUrl, Integer.parseInt(proxyPort));
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        
        HttpGet get = new HttpGet(uri);
        try {
            HttpResponse resonse = client.execute(get);
            if (resonse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = resonse.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            client.getConnectionManager().shutdown();
        }
        log.error("获取文件失败！[url=" + uri + "]");
        return new byte[0];
    }
    
    public static void main(String[] args) {
        try {
            download("http://mp3-2.manhuaju.com/青雪版_盗墓笔记第一季/1.mp3?vsid=05fe11dd3b035189eced346007bf81a9&l=1", "1.flv");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
